package com.prs.crm.dao.stock.impl;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.context.ToolKits;
import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.stock.ProductClassDao;
import com.prs.crm.domain.stock.ClassAttribute;
import com.prs.crm.domain.stock.ProductClass;

public class ProductClassDaoImpl extends BaseDaoImpl<ProductClass> implements ProductClassDao {

	
	public  ClassAttribute getAttribute(Integer attrId)
	{
		return (ClassAttribute)this.getHibernateTemplate().load(ClassAttribute.class, attrId);
	}
	
	@SuppressWarnings("unchecked")
	public Collection<ProductClass> findRootClasses()
	{
		return (Collection<ProductClass> )getHibernateTemplate().execute(   
			      new HibernateCallback() {   
			        public Object doInHibernate(Session session) throws HibernateException {   
			        	Criteria criteria =  session.createCriteria(ProductClass.class);
			        	criteria.add(Restrictions.isNull("parent"));
			        	return criteria.list();
			        }   
			      }   
			    );  
	}
	
	@SuppressWarnings("unchecked")
	public Collection<ProductClass> getProductClasses()
	{
		return (Collection<ProductClass> )getHibernateTemplate().execute(   
			      new HibernateCallback() {   
			        public Object doInHibernate(Session session) throws HibernateException {   
			        	Criteria criteria =  session.createCriteria(ProductClass.class);
			        	return criteria.list();
			        }   
			      }   
			    );  
	}
	
	public int removeAttributes(final Integer[] attrIds)
	{
		return (Integer)getHibernateTemplate().execute(   
			      new HibernateCallback() {   
			        public Object doInHibernate(Session session) throws HibernateException {   
			        	String hql = "delete from ClassAttribute where id in ("+ToolKits.constructInSql(attrIds)+")";
			        	return session.createQuery(hql).executeUpdate();
			        }   
			      }   
			    ); 
	}
}
